//
// Created by tang on 23-3-25.
//

#include "content/image.hpp"
#include "core/log.hpp"
#include "service/render_service.hpp"

thread_local IRenderService *renderService = nullptr;

static bool init_render_service() {
    if (renderService == nullptr) {
        renderService = ServiceManager::instance()->request_service<IRenderService>();
    }
    return renderService != nullptr;
}

ImageContent::ImageContent (const u8 *dat, u32 size) {
    if (init_render_service()) {
        img = renderService->create_image_from_content (dat, size);
        LC_FATAL (img== nullptr, "could not create image!! dat: %p, size: %u", dat, size);
    } else {
        L_ERROR("Failed to init render service!!");
    }
}
ImageContent::ImageContent (const std::string &path) {
    if (init_render_service()) {
        img = renderService->create_image_from_file (path);
        LC_FATAL (img== nullptr, "could not create image!! path: %s", path.c_str());
    } else {
        L_ERROR("Failed to init render service!!");
    }
}
ImageContent::~ImageContent () {
    if (init_render_service() && img) {
        renderService->free_image (img);
    }
    img = nullptr;
}
